package com.nbsaas.boot.sql;

import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectItem;

import java.util.ArrayList;
import java.util.List;

public class SelectFieldsExtractor {
    public static List<String> getSelectFields(String sql) {
        List<String> fields = new ArrayList<>();
        try {
            Statement statement = CCJSqlParserUtil.parse(sql);
            if (statement instanceof Select) {
                Select select = (Select) statement;
                PlainSelect plainSelect = (PlainSelect) select.getSelectBody();

                for (SelectItem item : plainSelect.getSelectItems()) {
                    fields.add(item.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }

    public static void main(String[] args) {
        String sql1 = "SELECT id, name, age FROM users WHERE age > 20";
        String sql2 = "SELECT u.id, u.name AS userName, COUNT(o.id) total FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name";

        System.out.println(getSelectFields(sql1));
        System.out.println(getSelectFields(sql2));
    }
}
